package com.tfswx.serialport;

import com.sun.jna.Platform;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.io.ClassPathResource;

import java.io.*;

/**
 * @author ricky
 * @date 2021/7/19
 */
@Slf4j
@SpringBootApplication
public class App {
    private static String[] fileNames = new String[]{"libmsprintsdk.so"};

    public static void main(String[] args) {
        if (Platform.isLinux()) {

            File libDir = new File("lib");
            if (!libDir.exists()) {
                boolean mkdirs = libDir.mkdirs();
                if (!mkdirs) {
                    throw new RuntimeException("lib文件夹创建失败");
                }
            }
            for (String fileName : fileNames) {
                File file = new File(libDir, fileName);
                if (file.exists()) {
                    continue;
                }
                ClassPathResource classPathResource = new ClassPathResource("lib/" + fileName);
                try (InputStream inputStream = classPathResource.getInputStream();
                     ByteArrayOutputStream bos = new ByteArrayOutputStream(inputStream.available())) {
                    byte[] buff = new byte[2048];
                    int len;
                    while ((len = inputStream.read(buff)) > 0) {
                        bos.write(buff, 0, len);
                    }
                    byte[] bytes = bos.toByteArray();
                    FileUtils.writeByteArrayToFile(file, bytes);
                    bos.flush();
                } catch (IOException e) {
                    log.error("{}文件拷贝失败", fileName, e);
                }
            }
        }
        SpringApplication app = new SpringApplication(App.class);
        app.setBannerMode(Banner.Mode.OFF);
        app.run(args);
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            log.info("java程序已经退出");
        }));
    }
}
